package com.zh.blog.util;

import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 复制对象或者集合属性的工具类
 * @author ZhengHao
 * Created At 2022/7/29.
 **/
public class BeanCopyUtils {

    /**
     * 复制对象
     *
     * @param source 源对象
     * @param target 目标对象
     * @return 返回
     */
    public static <T> T copyObject(Object source, Class<T> target){
        T temp = null;
        try {
            temp = target.newInstance();
            if (null != source){
                BeanUtils.copyProperties(source, temp);
            }
        } catch (Exception e){
            e.printStackTrace();
        }
        return temp;
    }

    /**
     *
     * @param source 源对象
     * @param target 目标对象
     * @return 返回集合
     */
    public static <T, S> List<T> copyList(List<S> source, Class<T> target){
        List<T> list = new ArrayList<>();
        if (null != source && source.size() > 0){
            for (Object obj : source) {
                list.add(BeanCopyUtils.copyObject(obj, target));
            }
        }
        return list;
    }
}